package com.hongxun.design.utils.mohe;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hongxun.design.R;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * Created by zerdoor_pc .
 * author:dc
 * 2016/12/26.
 */

public class BluetoothUtil2 {

    Activity context;
    BluetoothAdapter adapter;
    public BluetoothService mService;
    // Message types sent from the BluetoothService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    // Key names received from the BluetoothService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    Handler mHandler;
    AlertDialog dialog;
    LinearLayout liner_list;

    boolean isconnect=false;
    static BluetoothUtil2 instence;
    public static BluetoothUtil2 getInstence(){
        if (instence==null){
            instence=new BluetoothUtil2();
        }
        return instence;
    }
      BluetoothUtil2() {

    }

    public BluetoothUtil2 init(Activity context, Handler mHandler){
        this.context = context;
        this.mHandler = mHandler;

        return instence;
    }

    public void OPenDialog
            (){
        dialogForCreatePro();
    }

    /**
     * 检查手机是否支持蓝牙
     **/
    public boolean check() {
        adapter = BluetoothAdapter.getDefaultAdapter();
        return adapter != null;
    }

    /**
     * 打开蓝牙
     **/
    public void checkIsOpen() {
        if (adapter == null) adapter = BluetoothAdapter.getDefaultAdapter();
        // 打开蓝牙
        if (!adapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            // 设置蓝牙可见性，最多300秒
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            context.startActivityForResult(intent, 200);
        } else {
            getHas();
        }


        if (mService == null) {
            mService = new BluetoothService(context, mHandler);
        }
    }

    public boolean getStauts(){
        if (adapter == null) adapter = BluetoothAdapter.getDefaultAdapter();
        // 打开蓝牙
        return !(!adapter.isEnabled() || !isconnect);
    }


    public boolean isconnect() {
        return isconnect;
    }

    public void setIsconnect(boolean isconnect) {
        this.isconnect = isconnect;
    }

    /**
     * 获取已配对的蓝牙设备
     **/
    public void ensureDiscoverable() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> devices = adapter.getBondedDevices();

        for (int i = 0; i < devices.size(); i++) {
            final BluetoothDevice device = devices.iterator().next();
            System.out.println("bluetooth:getName=" + device.getName());
            System.out.println("bluetooth:getType=" + device.getType());
            System.out.println("bluetooth:getAddress=" + device.getAddress());
            System.out.println("bluetooth:getBluetoothClass=" + device.getBluetoothClass());
            System.out.println("bluetooth:getBondState=" + device.getBondState());
            System.out.println("bluetooth:getUuids=" + device.getUuids());
            TextView textView = new TextView(context);
            textView.setText("设备名称" + device.getName() + "\n地址： " + device.getAddress());
            textView.setTextColor(Color.WHITE);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    connectDevice(device);
                }
            });

        }
    }

    /**
     * 链接指定设备
     **/

    public void connectDevice(BluetoothDevice device) {

        name = device.getName();

//        BluetoothDevice deviceadress = adapter.getRemoteDevice(device.getAddress());
//        // Attempt to connect to the device
//        mService.connect(deviceadress);

        int connectState = device.getBondState();
        switch (connectState) {
            // 未配对
            case BluetoothDevice.BOND_NONE:
                // 配对
                try {
                    Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
                    createBondMethod.invoke(device);
                } catch (Exception e) {
                    System.out.println("bluetooth:配对e=" + e.toString());
                }
                break;
            // 已配对
            case BluetoothDevice.BOND_BONDED:
                try {
                    // 连接
                    connect(device);
                } catch (IOException e) {

                    System.out.println("bluetooth:连接e=" + e.toString());
                }
                break;
        }
    }

    /**
     * 搜索周围的蓝牙设备
     **/
    public void getHas() {
        // 设置广播信息过滤

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        // 注册广播接收器，接收并处理搜索结果
        context.registerReceiver(receiver, intentFilter);
        // 寻找蓝牙设备，android会将查找到的设备以广播形式发出去
        if (adapter == null) {
            adapter.cancelDiscovery();
            adapter = BluetoothAdapter.getDefaultAdapter();
        }
        adapter.startDiscovery();

    }


    /**
     * 蓝牙设备的配对和状态监视
     **/
    String name = "";

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 获取查找到的蓝牙设备
                final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                System.out.println("bluetooth:" + device.getName());
                System.out.println("bluetooth:" + device.getAddress());
                System.out.println("bluetooth:" + device.getBluetoothClass());
                // 如果查找到的设备符合要连接的设备，处理
                TextView textView = new TextView(context);

                textView.setText("\n" + "\t\t\t设备名称" + device.getName() + "\n\t\t\t地址： " + device.getAddress() + "\n");
                textView.setTextColor(context.getResources().getColor(R.color.title));
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        connectDevice(device);
                    }
                });
                liner_list.addView(textView);
                View view = new View(context);

                view.setBackgroundColor(context.getResources().getColor(R.color.tabblack));
                liner_list.addView(view, RelativeLayout.LayoutParams.MATCH_PARENT, 1);
                //向dialog中加入

//                    if (device.getName().equalsIgnoreCase(name)) {
//                        // 搜索蓝牙设备的过程占用资源比较多，一旦找到需要连接的设备后需要及时关闭搜索
//                        adapter.cancelDiscovery();
//                        // 获取蓝牙设备的连接状态
//                      int  connectState = device.getBondState();
//                        switch (connectState) {
//                            // 未配对
//                            case BluetoothDevice.BOND_NONE:
//                                // 配对
//                                try {
//                                    Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
//                                    createBondMethod.invoke(device);
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                                break;
//                            // 已配对
//                            case BluetoothDevice.BOND_BONDED:
//                                try {
//                                    // 连接
//                                    connect(device);
//                                } catch (IOException e) {
//                                    e.printStackTrace();
//                                }
//                                break;
//                        }
//                    }
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
//                    // 状态改变的广播
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getName().equalsIgnoreCase(name)) {
                    int connectState = device.getBondState();
                    switch (connectState) {
                        case BluetoothDevice.BOND_NONE:
                            System.out.println("bluetooth:BluetoothDevice.BOND_NONE");
                            break;
                        case BluetoothDevice.BOND_BONDING:
                            System.out.println("bluetooth:BluetoothDevice.BOND_BONDING");
                            break;
                        case BluetoothDevice.BOND_BONDED:
                            try {
                                System.out.println("bluetooth:BluetoothDevice.BOND_BONDED");
                                // 连接
                                connect(device);
                            } catch (IOException e) {
                                System.out.println("bluetooth:连接2e=" + e.toString());

                            }
                            break;
                    }
                }
            }
        }
    };

    /**
     * 蓝牙设备的连接
     **/
    String adress = "";

    private void connect(BluetoothDevice device) throws IOException {
        context.unregisterReceiver(receiver);
        adress = device.getAddress();
//        BluetoothDevice deviceadress = adapter.getRemoteDevice(adress);
        // Attempt to connect to the device
        mService.connect(device);

//        // 固定的UUID
//        final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
//        UUID uuid = UUID.fromString(SPP_UUID);
//        BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
//        socket.connect();

    }


    public String getAdress() {
        return adress;
    }


    /**
     * 创建项目完成dialog*
     */
    public AlertDialog dialogForCreatePro() {


        if (dialog==null){
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_bluetooth, null);

            liner_list = (LinearLayout) view.findViewById(R.id.liner_list);
            TextView button_back = (TextView) view.findViewById(R.id.back_activity);
            TextView button_go = (TextView) view.findViewById(R.id.sure_restart);

            dialog = builder.create();
            button_back.setOnClickListener(new View.OnClickListener() {//返回
                @Override
                public void onClick(View view) {
                    liner_list.removeAllViews();
                    adapter.cancelDiscovery();
                    dialog.dismiss();
                }
            });
            button_go.setOnClickListener(new View.OnClickListener() {//完成
                @Override
                public void onClick(View view) {
                    liner_list.removeAllViews();
                    adapter.cancelDiscovery();
                    getHas();
                }
            });

//      dialog.setTitle("自定义输入");
            dialog.setView(view, 0, 0, 0, 0);
            dialog.setCancelable(false);//设置点击外部区域不消失
        }
        if  (!dialog.isShowing()){
            dialog.show();
            return dialog;
        }
        return dialog;
    }

    public void close() {
        if (dialog != null && dialog.isShowing()) dialog.dismiss();
    }

    public void destory() {
        try {
            if (dialog != null && dialog.isShowing()) dialog.dismiss();
            if (adapter != null) adapter.disable();
        }catch (Exception e){}

    }

}
